package com.itany.shop.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/15 9:06
 * Version:1.0-SNAPSHOT
 * Description:
 */
@WebServlet("/showCode")
public class CodeServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();

        BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.fillRect(0,0,50,25);
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
        graphics.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));
        String s = "0123456789qwertyuiopasdfghjklzxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 4; i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        String code = buffer.toString();
        request.getSession().setAttribute("code",code);
        System.out.println("验证码:"+code);
        graphics.drawString(code,5,18);
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }

}
